package com.suian.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class WSGatewayFilterFactory extends AbstractGatewayFilterFactory<WSGatewayFilterFactory.Config> {
    private static final Logger logger = LoggerFactory.getLogger(WSGatewayFilterFactory.class);
    public static final String PARAM_NAME = "param";

    public WSGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(PARAM_NAME);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return ((exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            if (request.getQueryParams().containsKey(config.param)) {
                request.getQueryParams().get(config.param).forEach(
                        value -> logger.info("==============局部过滤器==============={}={}", config.param, value)
                );
            }
            return chain.filter(exchange);
        });
    }

    public static class Config {
        private String param;


        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }
    }
}
